package reduce.fz.com.reduce.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;

import java.util.List;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.Tag;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.TabIndicator;
import reduce.fz.com.reduce.custom.TagListView;
import reduce.fz.com.reduce.custom.TagView;
import reduce.fz.com.reduce.fragment.SocietyListFragment;
import reduce.fz.com.reduce.fragment.UserListFragment;
import reduce.fz.com.reduce.fragment.VideoCardListFragment;
import reduce.fz.com.reduce.service.FindService;
import reduce.fz.com.reduce.util.InputMethodUtil;
import reduce.fz.com.reduce.util.ServiceBuilder;
import reduce.fz.com.reduce.util.SetUtil;

public class CommonSearchActivity extends BaseToolBarActivity {
    private View barView;
    //取消按钮
    private TextView mCancel;
    //搜索框
    private EditText mEtSearch;
    //清除按钮
    private ImageView mClear;
    //推荐标签布局
    private TagListView mTagList;
    private LinearLayout mLlTagList;
    private FragmentManager mFragmentManager;
    public List<Tag> videotags;
    public List<Tag> usertags;
    public List<Tag> societytags;
    private FindService findService = ServiceBuilder.builderFindService(null);
    private Fragment mCurrentFragment;
    //用户列表
    private UserListFragment userListFragment;
    //视频列表
    private VideoCardListFragment videoListFragment;
    //社团列表
    private SocietyListFragment societyListFragment;

    private TabIndicator mTiSearch;

    private FrameLayout mMainContainer;
    private List<String> searchTitles;
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(mEtSearch.getText().toString()))
                displyTagView(true);
        }
    };

    public void initTabIndicator() {
        mTiSearch.setTabLayoutWeight(1);
        String[] temp = getResources().getStringArray(R.array.tab_common_search);
        searchTitles = SetUtil.toList(temp);
        mTiSearch.setTitleList(searchTitles);

        mTiSearch.setOnTabSelectedListener(new TabIndicator.OnTabSelectedListener() {
            @Override
            public void onTabReselected(int position) {

            }

            @Override
            public void onTabSelected(int position) {
                switch (position) {
                    case 0:
                        searchtype=TYPE_SEARCH_VIDEO;
                        attachVideoListFragment();
                        break;
                    case 1:
                        searchtype=TYPE_SEARCH_USER;
                        attachUserListFragment();
                        break;
                    case 2:
                        searchtype=TYPE_SEARCH_SOCIETY;
                        attachSocietyListFragment();
                    default:
                        break;

                }
            }
        });
    }
    public void displyTagView(Boolean isDisplay) {
        if (isDisplay) {
            mLlTagList.setVisibility(View.VISIBLE);
            mMainContainer.setVisibility(View.GONE);
        } else {
            mLlTagList.setVisibility(View.GONE);
            mMainContainer.setVisibility(View.VISIBLE);
        }
    }

    public void initTabDisplay()
    {
        attachVideoListFragment();
        mTiSearch.setCurrentItem(0);
    }




    public void attachUserListFragment() {
        if (userListFragment == null) userListFragment = UserListFragment.createSearch();
        showFragment(userListFragment, "userlistfragment");
        displyTagView(true);
        mTagList.removeAllViews();
        mTagList.addTags(usertags);
    }


    public void attachVideoListFragment() {
        if (videoListFragment == null) videoListFragment = VideoCardListFragment.createSerach();
        showFragment(videoListFragment, "videoListfragment");
        displyTagView(true);
        mTagList.removeAllViews();
        mTagList.addTags(videotags);
    }

    public void attachSocietyListFragment() {
        if (societyListFragment == null) societyListFragment = SocietyListFragment.create(2);
        showFragment(societyListFragment, "societylistfragment");
        displyTagView(true);
        mTagList.removeAllViews();
        mTagList.addTags(societytags);
    }


    public Fragment getFragmentByContext(String name) {
        Fragment fragment = mFragmentManager.findFragmentByTag(name);
        return fragment;
    }


    public void showFragment(Fragment fragment, String cacheKey) {
        displayRightBtn(false);
        android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        //先确认如果和当前的fragment相同，则不做处理
        if (mCurrentFragment != null && mCurrentFragment == fragment) return;
        //从缓存中获取fragment
        Fragment cacheFragment = getFragmentByContext(cacheKey);
        if (mCurrentFragment != null)
            fragmentTransaction.detach(mCurrentFragment);
        if (cacheFragment != null ) {
            mCurrentFragment = cacheFragment;
            fragmentTransaction.attach(cacheFragment).commit();
        } else {
            mCurrentFragment = fragment;
            fragmentTransaction.add(R.id.main_container, fragment, cacheKey).commit();
        }
    }


    public void getVideoTags() {
        findService.loadRecommendTag(TYPE_SEARCH_VIDEO, new AbResponseListener<List<Tag>>(new TypeReference<Result<List<Tag>>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }

            @Override
            public void responseInfo(Result<List<Tag>> data) {
                videotags = data.getData();
                initTabDisplay();
            }
        });
    }

    public void getUserTags() {
        findService.loadRecommendTag(TYPE_SEARCH_USER, new AbResponseListener<List<Tag>>(new TypeReference<Result<List<Tag>>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }

            @Override
            public void responseInfo(Result<List<Tag>> data) {
                usertags = data.getData();
            }
        });
    }

    public void getSocietyTags() {
        findService.loadRecommendTag(TYPE_SEARCH_SOCIETY, new AbResponseListener<List<Tag>>(new TypeReference<Result<List<Tag>>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }
            @Override
            public void responseInfo(Result<List<Tag>> data) {
                societytags = data.getData();
            }
        });

    }

    public static final int TYPE_SEARCH_VIDEO = 0;
    public static final int TYPE_SEARCH_USER = 1;
    public static final int TYPE_SEARCH_SOCIETY = 2;
    private int searchtype = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_search);
        initWidget();
        mToolbar.removeAllViews();
        barView = getLayoutInflater().inflate(R.layout.bar_common_search, mToolbar,true);
       // mToolbar.addView(barView);
        mFragmentManager = getSupportFragmentManager();
        initBarView(barView);
        initRecommentTags();
        initTabIndicator();
        initListener();
        setTagListener();
    }

    public void initRecommentTags() {
        getVideoTags();
        getUserTags();
        getSocietyTags();
    }

    public void setTagListener() {
        mTagList.setOnTagClickListener(new TagListView.OnTagClickListener() {
            @Override
            public void onTagClick(TagView tagView, Tag tag) {
                mEtSearch.setText(tag.bname);
                InputMethodUtil.reuestFocusAndShowInput(mEtSearch);
            }
        });
    }

    /**
     * 初始化
     *
     * @param barView
     */
    public void initBarView(View barView) {
        mCancel = (TextView) barView.findViewById(R.id.tv_cancel);
        mEtSearch = (EditText) barView.findViewById(R.id.et_search);
        mClear = (ImageView) barView.findViewById(R.id.iv_clear);
        mClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearEdit();
            }
        });
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 清除用户输入框
     */
    public void clearEdit() {
        mEtSearch.setText("");
    }


    @Override
    public void initWidget() {
        mTiSearch = (TabIndicator) findViewById(R.id.ti_search);
        mTagList = (TagListView) findViewById(R.id.tag_recommend);
        mLlTagList=(LinearLayout)findViewById(R.id.ll_tag_recommend);
        mMainContainer = (FrameLayout) findViewById(R.id.main_container);

    }

    public void search() {
        displyTagView(false);
        String keyword=mEtSearch.getText().toString();
        switch (searchtype) {
            case TYPE_SEARCH_VIDEO:
                videoListFragment.searchVideo(keyword);
                break;
            case TYPE_SEARCH_USER:
                userListFragment.searchUser(keyword);
                break;
            case TYPE_SEARCH_SOCIETY:
                societyListFragment.research(keyword);
                break;
            default:
                break;
        }

    }


    @Override
    public void initListener() {
        mEtSearch.addTextChangedListener(watcher);
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                search();
                return false;
            }
        });
    }


}
